import requests
import re
import tkinter as tk
import tkinter.messagebox
import socket
import platform
import time
import configparser


# 判断网络是否连接（简单检测是否能访问常见网站，这里以百度为例）
def is_network_connected():
    try:
        socket.create_connection(("www.baidu.com", 80), 2)
        return True
    except OSError:
        return False


# 获取本地IP地址（尝试获取有线网卡IP，这里只是简单示例，可能不完全准确）
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception as e:
        print(f"获取IP地址出错: {e}")
        return None


# 发送登录请求
def login(username, password, ip):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
        "Host": "172.30.255.42"
    }
    url = "http://172.30.255.42"
    try:
        res2 = requests.get(url, headers=headers)
        res = re.compile(r"<script type=.*?>.*?v46ip='(?P<ip>.*?)'.*?", re.S)
        res1 = res.finditer(res2.text)
        for i in res1:
            ip = i.group("ip")

        url2 = f"http://172.30.255.42:801/eportal/portal/login?callback=dr1003&login_method=1&user_account=%2C0%2C{username}&user_password={password}&wlan_user_ip={ip}&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=4.1.3&terminal_type=1&lang=zh-cn&v=6230&lang=zh"
        res3 = requests.get(url2, headers=headers)
        return res3.text
    except requests.RequestException as e:
        print(f"登录请求出错: {e}")
        return None


# 保存登录信息到配置文件
def save_login_info(username, password):
    config = configparser.ConfigParser()
    config['Login'] = {'username': username, 'password': password}
    with open('login.ini', 'w') as configfile:
        config.write(configfile)


# 从配置文件读取登录信息
def read_login_info():
    config = configparser.ConfigParser()
    try:
        config.read('login.ini')
        return config.get('Login', 'username'), config.get('Login', 'password')
    except:
        return None, None


# GUI界面相关代码
def create_login_window():
    root = tk.Tk()
    root.title("校园网登录")
    root.geometry("300x200")

    # 从配置文件读取登录信息
    username, password = read_login_info()

    # 用户名标签和输入框
    username_label = tk.Label(root, text="用户名:")
    username_label.pack()
    username_entry = tk.Entry(root)
    username_entry.insert(0, username if username else "")
    username_entry.pack()

    # 密码标签和输入框
    password_label = tk.Label(root, text="密码:")
    password_label.pack()
    password_entry = tk.Entry(root, show="*")
    password_entry.insert(0, password if password else "")
    password_entry.pack()

    def on_login_click():
        username = username_entry.get()
        password = password_entry.get()
        if not is_network_connected():
            tkinter.messagebox.showerror("错误", "网络未连接，请检查网络！")
            return
        local_ip = get_local_ip()
        if local_ip is None:
            tkinter.messagebox.showerror("错误", "获取本地IP地址失败，请检查网络设置！")
            return
        result = login(username, password, local_ip)
        if result:
            save_login_info(username, password)
            tkinter.messagebox.showinfo("提示", "登录成功！")
        else:
            tkinter.messagebox.showerror("错误", "登录失败，请检查用户名、密码是否正确！")

    # 自动登录尝试（程序启动时）
    if username and password:
        if is_network_connected():
            local_ip = get_local_ip()
            
    # 登录按钮
    login_button = tk.Button(root, text="登录", command=on_login_click)
    login_button.pack()

    root.mainloop()


if __name__ == "__main__":
    create_login_window()